from google.appengine.api.urlfetch import fetch
import logging
from pplsearch.models import *
import sys
import random

def analyze_description(description):
    words = description.split()
    concepts = []
    for w in words:
        #if w == w.capitalize() or w == w.upper():
        if w[0]>='A' and w[0]<="Z":
            concepts.append(w.strip(";,.?!"))
    return concepts
    
    
    
def search_ppl_by_concepts(concepts):
    results = []
    already_appeared = {}
    is_first = True
    for concept in concepts:
        #try:
        rel = ConceptHumanRelation(concept, [])
        logging.debug("created rel for %s. it has %d ppl" % (rel.concept, len(rel.ppl)))
        url = "http://search.twitter.com/search.atom?q=%s" % concept
        xml = fetch(url).content
        pos = 0
        while xml.find("<name>", pos) >= 0:
            pos = xml.find("<name>", pos) + len("<name>")
            end_pos = xml.find("</name>", pos)
            person = xml[pos:end_pos]
            delim_pos = person.find(" ")
            nickname = person[:delim_pos]
            if not rel.has_person(nickname):
                logging.debug("found %s" % nickname)
                # add only if its the first concept, or the person already appeared in previous concepts.
                if is_first or already_appeared.has_key(nickname):
                    logging.debug("adding %s to %s" % (nickname, concept))
                    rel.add_person(nickname)
                    already_appeared[nickname] = True
            pos = end_pos
        logging.debug("added %d ppl to %s" % (len(rel.ppl), rel.concept))
        is_first = False
        #if rel.has_people():
        logging.debug("adding concept %s which has %d ppl" % (rel.concept, len(rel.ppl)))
        results.append(rel)
        #except:
        #    print sys.exc_info()
    logging.debug(results)
    return results
    
    
def mock_search_ppl_by_concepts(concepts):
    results = []
    for concept in concepts:
        rel = ConceptHumanRelation(concept, [])
        n = random.choice(range(10))
        for i in range(n):
            rel.add_person("%s_%d" % (concept, i))
        results.append(rel)
    return results

def get_person_entries(nickname):
    results = []
    url = "http://search.twitter.com/search.atom?q=from%%3A%s" % nickname
    logging.debug("Fetching entries from %s" % url)
    xml = fetch(url).content
    pos = 0
    while xml.find("<entry>", pos) >= 0:
        pos = xml.find("<title>", pos) + len("<title>")
        end_pos = xml.find("</title>", pos)
        title = xml[pos:end_pos]
        title = title.strip("'")
        pos = pos = xml.find("<updated>", end_pos) + len("<updated>")
        end_pos = xml.find("</updated>", pos)
        update_time = xml[pos:end_pos]
        pos = pos = xml.find("<name>", end_pos) + len("<name>")
        end_pos = xml.find("</name>", pos)
        name = xml[pos:end_pos]
        pos = end_pos
        logging.debug("adding entry %s by %s updated on %s" % (title, name, update_time))
        entry = Entry(name, title, update_time)
        results.append(entry)
        #except:
        #    print sys.exc_info()
    logging.debug(results)
    return results
    
def mock_get_person_entries(nickname):
    results = []
    n = 5
    for i in range(n):
        entry = Entry(nickname, "entry-%d" % i, "updated on %d" % i)
        results.append(entry)
    logging.debug(results)
    return results
